// pages/me/pages/rencai/index.js
import { input } from '../../../../utils/tools'
import { formatTime, formatTime1, formatTime2, date, hour, getAge } from '../../../../utils/util'
const XLSX = require('../../../../utils/excel.js')
import { url } from '../../../../utils/config'
const {
	http
} = require("../../../../utils/apiutils")
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		dataList: [],
		pageNo: 1,
		pageSize: 10,
		hasMore: true,
		loading: false,
		sxshow: false,
		dateshow: false,
		radio: 1,
		actIcon: 'http://linghuoimage.xbbzp.com/FlKr6FRsslyAM9qrcz8LSlIaJkYM',
		icon: 'http://linghuoimage.xbbzp.com/Fk8gN24U6sEA3-Dj6Fj76Pk9W1W3',
		currentDate: new Date().getTime(),
		minDate: new Date('2015-01-01').getTime(),
		formatter(type, value) {
			if (type === 'year') {
				return `${value}年`;
			}
			if (type === 'month') {
				return `${value}月`;
			}
			return value;
		},
		dateKey: '',
		showedit: false,
		faceType: 1,
		queryParams: {
			start: '',
			end: '',
			searchKey: '',
			batch: "1",   //  全部0  最近1
			status: "0",  //  待入职1  2待离职  3在职   0全部
			record: "0",  // 1未沟通  2已沟通  0全部
		},
		checkArr: [],
		showBtnType: 1,
		allChecked: false,
		editInfo: {},
		editIndex: 0,
		editType: 1,// 编辑 按钮类型
		showedit2: false,
		editInfo2: {},
		hasClear: false, hasClear: false,
		pageNo: 1,
		pageSize: 20
	},

	input(e) {
		input.bind(this)(e)
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {

	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.data.hasMore=true;
		this.getList()
		let face = wx.getStorageSync('face');
		this.setData({
			faceType: face || 1,
			showBtnType: 1
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {


	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	},
	onInput(value) {
		this.setData({
			dateKey: '',
			["queryParams." + this.data.dateKey]: formatTime(value.detail),
			dateshow: false
		})
		// if (this.data.dateKey == 'start') { 

		// }
		// if (this.data.dateKey == 'end') { 
		// 	this.setData({
		// 		dateKey: '',
		// 		["queryParams.endDate"]:formatTime(value.detail)
		// 	})
		// }



	},
	showDate(e) {
		let key = e.currentTarget.dataset.key;
		this.setData({
			dateKey: key,
			dateshow: true
		})
	},
	cancel() {
		this.setData({
			dateKey: '',
			dateshow: false
		})
	},
	setsxshow() {
		this.setData({
			sxshow: true
		})
	},
	onChange(e) {
		let key = e.target.dataset.key
		this.setData({
			[key]: e.detail
		})
	},
	checkchange(e) {
		let index = e.target.dataset.index;
		let arr = [...this.data.checkArr];
		let dataList = [...this.data.dataList];
		if (e.detail) {
			dataList[index].checked = true
			arr.push(index)
		} else {
			let delIndex = arr.indexOf(index);
			arr.splice(delIndex, 1);
			dataList[index].checked = false
		}
		this.setData({
			dataList: [...dataList],
			checkArr: [...arr],
			showBtnType: arr.length > 0 ? 2 : 1
		})
	},
	cancelclick() {
		this.setData({
			sxshow: false
		})
	},
	cancelEdit() {
		this.setData({
			showedit: false,
			showedit2: false,
			editInfo: {},
			editInfo2: {},
			editIndex: 0
		})
	},
	changeface() {
		let face = this.data.faceType == 1 ? 2 : 1
		this.setData({
			faceType: face
		})
		wx.setStorageSync('face', face)
	},
	importRc() {
		wx.navigateTo({
			url: '../importRc/index'
		})
	},
	edit(e) {
		let index = e.currentTarget.dataset.index;
		let params = {
			...this.data.dataList[index]
		}
		let arr = ['已接到', '异常', '在职', '已录用', '已报名'];
		let status = arr.indexOf(params.status) * 1 + 1;
		console.log(status)
		this.setData({
			showedit: true,
			editIndex: index,
			editInfo: {
				status: status,
				intention: params.intention,
				remark: params.remark,
				record: params.record
			}
		})
	},
	searchchange(data) {
		this.setData({
			['queryParams.searchKey']: data.detail
		})
	},
	getList() {
		console.log('999')
		if (!this.data.hasMore) {
			return false;
		}
		let params = {
			searchKey: this.data.queryParams.searchKey,
			batch: this.data.queryParams.batch == 0 ? "" : this.data.queryParams.batch,
			status: this.data.queryParams.status == 0 ? "" : this.data.queryParams.status,
			record: this.data.queryParams.record == 0 ? "" : this.data.queryParams.record,
			start: this.data.queryParams.start,
			end: this.data.queryParams.end,
			pageNo: this.data.pageNo,
			pageSize: this.data.pageSize
		}
		http.searchTalents(params, res => {
			if (res.status == 200) {
				if (res.obj.data.records.length > 0) {
					res.obj.data.records.map(item => {
						try {
							item.checked = false;
							let time = new Date()
							if (item.createTime) {
								time = item.createTime.replace(/-/g, '/')
							}
							if (item.updateTime) {
								time = item.updateTime.replace(/-/g, '/')
							}
							item.time = formatTime(time);
							item.age = getAge(item.talentId);
							let guoqi = item.validity ? item.validity.split('-') : ''
							item.guoqi = false;
							if (guoqi) {
								let end = guoqi[1].substr(0, 4) + '/' + guoqi[1].substr(4, 2) + '/' + guoqi[1].substr(6);
								if (new Date('2025-02-03').getTime() > new Date(end).getTime()) {
									item.guoqi = true;
								}
							}
						} catch (error) {
							console.log('列表循环出错')
						}

					})
					wx.nextTick(_ => {
						this.setData({
							dataList: [...this.data.dataList, ...res.obj.data.records],
							sxshow: false,
							pageNo: this.data.pageNo + 1,
							hasClear: res.obj.batch
						})
					})
				} else {
					this.data.hasMore = false;
					this.data.pageNo = 1
				}
				// this.setData({
				// 	dataList: [...this.data.dataList,...res.obj.data.records],
				// 	sxshow: false,
				// 	pageNo:this.data.pageNo+1,
				// 	hasClear: res.obj.batch
				// })
			} else {
				wx.showToast({
					title: res.msg,
					icon: "none"
				})
			}
		}, err => { })
	},
	making(e) {
		let tel = e.currentTarget.dataset.tel;
		if (!tel) {
			wx.showToast({
				title: '未记录电话',
				icon: "none"
			})
			return false;
		}
		wx.makePhoneCall({
			phoneNumber: tel,
		})
	},
	checkAllChange(e) {
		let arr = [...this.data.dataList];
		let checkArr = [];
		arr.map((item, index) => {
			item.checked = e.detail;
			if (e.detail) {
				checkArr.push(index)
			}
		})
		this.setData({
			dataList: arr,
			checkArr: checkArr,
			allChecked: e.detail,
			showBtnType: e.detail ? 2 : 1
		})
	},
	oneUpdateEdit() {
		let params = {
			ids: [this.data.dataList[this.data.editIndex].id],
			...this.data.editInfo
		}
		this.updateEdit(params)
	},
	allUpdateEdit() {
		if (!this.data.checkArr.length) {
			return false;
		}
		let _this = this;
		let ids = [];
		this.data.dataList.map((item, index) => {
			if (_this.data.checkArr.includes(index)) {
				ids.push(item.id)
			}
		})
		let params = {
			ids: [...ids],
			...this.data.editInfo2
		}
		this.updateEdit(params)
	},
	updateEdit(params) {
		http.talentPoolUpdate(params, res => {
			if (res.status == 200) {
				this.setData({
					editInfo: {},
					editInfo2: {},
					editIndex: 0,
					showedit: false,
					showedit2: false,
					checkArr: [],
					showBtnType: 1,
					editIndex: 0,
				})
				this.oksearch()
			} else {
				wx.showToast({
					title: res.msg,
					icon: "none"
				})
			}
		}, err => { })
	},
	edit2(e) {
		this.setData({
			showedit2: true,
			editInfo2: {
				status: '',
				record: '',
				intention: ''
			}
		})
	},
	clearlist() {
		let _this = this;
		wx.showModal({
			title: '清空',
			content: '您确认清空当前批次吗?',
			confirmText: '是',
			cancelText: '否',
			success(res) {
				if (res.confirm) {
					http.clearTheBatch({}, res => {
						if (res.status == 200) {
							_this.oksearch()
						} else {
							wx.showToast({
								title: res.msg,
								icon: "none"
							})
						}
					}, err => { })
				}
			}
		})

	},
	clickPeople(e) {
		// console.log('---',e.currentTarget.dataset.key)
		wx.navigateTo({
			url: '/pages/clock/pages/personalInfo/personalInfo?id=' + e.currentTarget.dataset.key,
		})
	},
	exportExcle() {
		let data = [];
		let _this = this;
		this.data.dataList.map((item, index) => {
			if (_this.data.checkArr.includes(index)) {
				let arr = [
					item.talentName,
					item.gender,
					item.age,
					item.nation,
					item.talentId,
					item.talentPhone,
					item.addr,
					item.validity,
					item.updateTime,
					item.intention,
					item.status,
					item.record
				];
				data.push(arr)
			}
		})
		let sheet = []
		let title = ['姓名', '性别', '年龄', '民族', '身份证号', '电话', '住址', '有效期', '操作时间', '岗位', '状态', '备注']
		sheet.push(title)
		sheet.push(...data)
		var ws = XLSX.utils.aoa_to_sheet(sheet);
		var wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "人才库");
		var fileData = XLSX.write(wb, {
			bookType: "xlsx",
			type: 'base64'
		});
		var timestamp = Date.parse(new Date());
		var date = new Date(timestamp);
		//获取年份  
		var Y = date.getFullYear();
		//获取月份  
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		//获取当日日期 
		var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
		console.log("当前时间：" + Y + '年' + M + '月' + D + '日');
		var hour = date.getHours()
		var minute = date.getMinutes()
		var second = date.getSeconds()
		let filePath = `${wx.env.USER_DATA_PATH}/${getApp().globalData.userInfo.realName}${formatTime(new Date())}.xlsx`

		// 写文件
		const fs = wx.getFileSystemManager()
		fs.writeFile({
			filePath: filePath,
			data: fileData,
			encoding: 'base64',
			success(res) {
				console.log(res)
				const sysInfo = wx.getSystemInfoSync()
				// 导出
				if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
					// 电脑PC端导出
					wx.saveFileToDisk({
						filePath: filePath,
						success(res) {
							console.log(res)
						},
						fail(res) {
							console.error(res)
							util.tips("导出失败")
						}
					})
				} else {
					// 手机端导出
					// 打开文档
					wx.openDocument({
						filePath: filePath,
						showMenu: true,
						success: function (res) {
							console.log(res)
						},
						fail: console.error
					})
				}

			},
			fail(res) {
				if (res.errMsg.indexOf('locked')) {
					wx.showModal({
						title: '提示',
						content: '文档已打开，请先关闭',
					})
				}

			}
		})
	},
	/**
* 导入
*/
	uploadData() {
		const that = this
		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			success(res) {
				console.log(res.tempFiles[0])
				const path = res.tempFiles[0].path
				let size = res.tempFiles[0].size;
				let filename = res.tempFiles[0].name;
				// &&filename.indexOf(".xlsx") == -1
				if (filename.indexOf(".xls") == -1) { //限制文件类型
					wx.showModal({
						title: '提示',
						content: '文件类型必须为excel！(.xls)',
						confirmColor: '#0177ff',
						confirmText: '确定',
						success: function (res) { },
					})
				} else {
					wx.showModal({
						title: '提示',
						content: '确定上传' + filename + "?",
						confirmColor: '#0177ff',
						confirmText: '上传',
						success: function (res) {
							if (res.confirm) {
								wx.showLoading({
									title: "上传中",
								});
								wx.uploadFile({
									url: url + '/api/upload/file', //上传的路径
									header: {
										"content-type": "application/vnd.ms-excel",
										"Authorization": "Bearer " + getApp().globalData.token
									},
									filePath: path,
									name: 'file', //后台获取的凭据
									success(res) {
										wx.hideLoading()
										let resp = JSON.parse(res.data)
										let pathArr = resp.data.split('/');
										if (resp.code == 0) {
											that.importRck(pathArr[pathArr.length - 1])
										} else {
											wx.showToast({
												title: '上传失败',
												icon: "none"
											})
										}
									},
									fail(err) {
										wx.hideLoading();
										wx.showModal({
											title: '提示',
											content: "文件上传失败" + err.errMsg,
											showCancel: false, //是否显示取消按钮
											success: function (result) {
											}
										})
									}
								})
							}
						}
					})
				}

			}
		})
	},
	importEx() {
		let system1 = wx.getFileSystemManager();
		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			success(res) {
				console.log(res.tempFiles[0])
				const path = res.tempFiles[0].path
				let size = res.tempFiles[0].size;
				let filename = res.tempFiles[0].name;
				// &&filename.indexOf(".xlsx") == -1
				if (filename.indexOf(".xls") == -1) { //限制文件类型
					wx.showModal({
						title: '提示',
						content: '文件类型必须为excel！(.xls)',
						confirmColor: '#0177ff',
						confirmText: '确定',
						success: function (res) { },
					})
				} else {
					system1.readFile({
						filePath: path,
						success(res) {
							console.log(res)
						}
					})
				}
			}
		})
	},
	importRck(path) {
		let params = {
			path: path
		};
		http.importRck(params, res => {
			if (res.status == 200) {
				wx.showToast({
					title: '上传成功',
					icon: "none"
				})
				this.oksearch()
			} else {
				wx.showToast({
					title: res.msg,
					icon: "none"
				})
			}
		}, err => {

		})
	},
	resetDate() {
		this.setData({
			['queryParams.start']: '',
			['queryParams.end']: ''
		})
	},
	view() { },
	oksearch() {
		this.setData({
			dataList: [],
			pageNo: 1,
			hasMore: true
		})
		this.getList()
	}
})